import { defineStore } from 'pinia';
import { pathJoin } from 'src/api/SysApi';
import { getFile, saveFile }                         from 'src/api/FileApi';
import { useConfigStore }                            from 'stores/configStore';
import { getTmsTemplateById, GetTmsTemplateByIdRes } from 'src/api/api';
import { useYmlStore }                               from 'stores/ymlStore';
import LoginLayout                                   from 'layouts/LoginLayout.vue';

export const useTemplateStore = defineStore('template', () => {
  //操作
  const getTemplateContentByPath = (path: string) => {
    return new Promise((resolve) => {
      getFile(path, false).then((r: string) => {
        resolve(r);
      });
    });
  };

  const getTemplateContentById = (id: number) => {
    return new Promise(async (resolve) => {
      const path = pathJoin(
        <string>useConfigStore().config.templateFilePath,
        id.toString() + '.gen'
      );
      getFile(path, false).then(async (r: string) => {
        console.log(path);
        if (r === '文件不存在') {
          console.log('文件不存在');
          getTmsTemplateById(id).then((res: GetTmsTemplateByIdRes) => {
            useTemplateStore().saveTemplateContentById(
              id,
              res.data.data.content
            );
            const content = res.data.data?.content;
            delete res.data.data?.content;
            useYmlStore().saveYmlContentByName('template-' + id, res.data.data);
            resolve({ ...res.data.data, content: content });
          });
        } else {
          console.log('文件存在');
          const data = await useYmlStore().getYmlContentByName(
            'template-' + id
          );
          resolve({ ...data, content: r });
        }
      });
    });
  };
  const saveTemplateContentByPath = (path: string, data: string) => {
    return new Promise((resolve) => {
      saveFile(path, data).then((r: string) => {
        resolve(r);
      });
    });
  };
  const saveTemplateContentById = (id: number, data: string) => {
    return new Promise(async (resolve) => {
      saveFile(
        pathJoin(
          <string>useConfigStore().config.templateFilePath,
          id.toString() + '.gen'
        ),
        data
      ).then((r: string) => {
        resolve(r);
      });
    });
  };

  return {
    getTemplateContentByPath,
    getTemplateContentById,
    saveTemplateContentByPath,
    saveTemplateContentById,
  };
})
